using System.Collections;
using UnityEngine;

public class Enemy : MonoBehaviour
{
    public Transform player;
    [Header("移动速度")]
    public float speed = 3f;
    [Header("生命值")]
    public float health = 100f;
    [Header("敌人类型")]
    public int type;
    [Header("攻击距离")]
    public float AttackDistance = 0.5f;
    [Header("是否是反转鸟")]
    public bool IsReverseBird = false;
    [Header("反转鸟的颜色")]
    public Color revColor;
    [Header("反转鸟的生命值")]
    public float revHealth = 100f;
    public bool IsDied = false;
    public GameController gameController;
    public bool IsAttacking;
    public Animator animator;
    public Vector3 RandomOffset;
    public bool IsBeingHitBack;
    [Header("被击飞的距离")]
    public float DistanceOfHitBack = 1f;


    // 固定时长飞行相关字段
    public bool IsFlying = false;
    [Header("被击飞时飞行速度")]
    public float FlySpeed = 10f;
    private Vector3 _flyStartPos;
    private Vector3 _flyTargetPos;
    private float _flyDuration = 0.5f;
    private float _flyElapsed = 0f;
    void Start()
    {
        gameController = GameObject.Find("GameController").GetComponent<GameController>();
        player = GameObject.FindGameObjectWithTag("Player").transform;
        // SelectSpriteByType();        
        InvokeRepeating(nameof(PlayMoveSFX), 0, 2f);
        // 反转鸟的颜色和生命值会发生变化
        if (IsReverseBird)
        {
            GetComponent<SpriteRenderer>().color = revColor;
            health = revHealth;
        }
    }

    //移动音效
    void PlayMoveSFX()
    {
        if (GameManager.Instance.IsGameOver)
        {
            CancelInvoke();
            return;
        }
        AudioManager.Instance.PlaySFX(3);
    }

    //甩头音效
    void PlayAtkSFX()
    {
        AudioManager.Instance.PlaySFX(2);
    }

    //丢虫子音效
    void PlayThrowSFX()
    {
        AudioManager.Instance.PlaySFX(1);
    }

    //鸟被打音效
    void PlayTakeDamageSFX()
    {
        AudioManager.Instance.PlaySFX(4);
    }

    void Update()
    {
        if (GameManager.Instance.IsGameOver)
        {
            return;
        }
        if (IsFlying)
        {
            _flyElapsed += Time.deltaTime;
            float t = Mathf.Clamp01(_flyElapsed / _flyDuration);
            transform.position = Vector3.Lerp(_flyStartPos, _flyTargetPos, t);
            return;
        }
        if (player != null &&
        !IsAttacking &&
        !IsDied &&
        !player.GetComponent<Player>().IsBeingAttacked &&
        !player.GetComponent<Player>().IsFlying)
        {
            Move();
            // 计算与人机距离
            float distance = Vector3.Distance(transform.position, player.position);
            if (distance <= AttackDistance) {
                StartCoroutine(Attack());
            }
        }
    }

    // public void SelectSpriteByType()
    // {
    //     if (sprites.Length > 0 && spriteRenderer != null)
    //     {
    //         spriteRenderer.sprite = sprites[type];
    //     }
    // }
    public void Move()
    {
        // 朝玩家移动，但是添加一个随机的偏移量
        
        Vector3 direction = (player.position - transform.position).normalized;
        transform.Translate(direction * speed * Time.deltaTime, Space.World);
        // 朝向玩家（左右）
        if (direction.x > 0)
        {
            transform.localScale = new Vector3(1, 1, 1);
        }
        else if (direction.x < 0)
        {
            transform.localScale = new Vector3(-1, 1, 1);
        }
        animator.SetBool("IsMoving", true);
    }

    public IEnumerator TakeDamage(float damage, float delay)
    {
        yield return new WaitForSeconds(delay);
        // 这里是鸟被打
        PlayTakeDamageSFX();
        health -= damage;
        if (health <= 0)
        {
            Die();
        } else
        {
            animator.SetTrigger("Hit");
        }
    }

    public IEnumerator Attack()
    {
        if (IsAttacking || player.GetComponent<Player>().IsFlying || player.GetComponent<Player>().IsBeingAttacked == true || player.GetComponent<Player>().IsDashing) yield break;
        // 开始甩头
        if (IsReverseBird)
        {
            GameObject.Find("BUG").GetComponent<Movement>().reverse = true;
            AudioManager.Instance.PlaySFX(14);
            
        } else
        {
            GameObject.Find("BUG").GetComponent<Movement>().reverse = false;
        }
        player.GetComponent<Player>().StartCoroutine(player.GetComponent<Player>().BeAttacked());
        PlayAtkSFX();
        animator.SetTrigger("Attack");
        IsAttacking = true;
        yield return new WaitForSeconds(0.5f);
        animator.SetTrigger("AttackOver");
        PlayThrowSFX();
        yield return new WaitForSeconds(0.3f);
        IsAttacking = false;
    }

    public IEnumerator BeHitBack(Vector3 oriPlayerPos)
    {
        Vector3 direaction = (oriPlayerPos - transform.position).normalized;
        Vector3 toPos = -DistanceOfHitBack * direaction;
        StartCoroutine(TakeDamage(20, 0));
        yield return StartFly(toPos + transform.position);               
    }
    public IEnumerator StartFly(Vector3 toPosition)
    {
        StartFlyTo(toPosition);
        yield return new WaitForSeconds(_flyDuration);
        IsFlying = false;
    }

    // 开始一个基于距离自动计算时长的飞行动作（duration = distance / FlySpeed）
    public void StartFlyTo(Vector3 toPosition)
    {
        _flyStartPos = transform.position;
        _flyTargetPos = toPosition;
        float distance = Vector3.Distance(_flyStartPos, _flyTargetPos);
        float effectiveSpeed = Mathf.Max(0.0001f, FlySpeed);
        _flyDuration = distance / effectiveSpeed;
        _flyElapsed = 0f;
        IsFlying = true;
    }

    public void Die()
    {
        animator.SetTrigger("Die");
        IsDied = true;
        gameController.IncreaseKillCount(1);
        // 更改Tag以防止再次被攻击
        gameObject.tag = "Untagged";
        Destroy(gameObject, 1f);
        CancelInvoke();
    }
}